package com.easemob.helpdesk.activity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.helpdesk.bean.UploadResult;
import com.easemob.helpdesk.widget.LinePathView;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;


import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * Created by xiaolong.wei on 2019/7/24.
 */

public class HandSignActivity extends BaseActivityV2 {

    private static final String TAG = "HandSignActivity";


    LinePathView linePathView;
    Bitmap mBitmap;
//    @BindView(R.id.clear)
//    TextView clear;
//    @BindView(R.id.save)
//    TextView save;
//    @BindView(R.id.sign)
//    ImageView sign;
    ProgressBar mProgressBar;
    File bitmapFile;
    private int orderId;

    TextView clear,save;

    @Override
    protected void initFindView() {
        super.initFindView();
        linePathView=findViewById(R.id.line_path_view);
        mProgressBar=findViewById(R.id.progressBar);
        clear=findViewById(R.id.clear);

        save=findViewById(R.id.save);

        clear.setOnClickListener(view -> linePathView.clear());

        save.setOnClickListener(view -> {
            if (linePathView.isPaint()) {
                mProgressBar.setVisibility(View.VISIBLE);
                mBitmap = linePathView.saveToBitmap(true, 0);
//                sign.setImageBitmap(mBitmap);
                PermissionGen
                        .with(this)
                        .addRequestCode(100)
                        .permissions(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                        .request();
            }else {
                Toast.makeText(HandSignActivity.this,"您还没有签名",Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hand_sign_activity);
        initFindView();
        linePathView.setPaintWidth(10);
        linePathView.setPenColor(Color.parseColor("#565656"));
        orderId = getIntent().getIntExtra("ORDER_ID",-1);
    }

/*    @OnClick({R.id.clear, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear:
//                test();
                linePathView.clear();
                break;
            case R.id.save:
                if (linePathView.isPaint()) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mBitmap = linePathView.saveToBitmap(true, 0);
//                sign.setImageBitmap(mBitmap);
                    PermissionGen
                            .with(this)
                            .addRequestCode(100)
                            .permissions(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                            .request();
                }else {
                    Toast.makeText(HandSignActivity.this,"您还没有签名",Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }*/



    @PermissionSuccess(requestCode = 100)
    private void cacheSignBitmap(){
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/housekeeper/cache");
        if (!file.exists()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try {
                    Path directories = Files.createDirectories(file.toPath());
                    Log.d(TAG, "cacheSignBitmap: "+directories.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                boolean mkdir = file.mkdirs();
                Log.d(TAG, "cacheSignBitmap: "+mkdir);
            }
        }
        String fileName = "/sign"+System.currentTimeMillis()+".png";
        FileOutputStream fileOutputStream = null;
        try {
            bitmapFile = linePathView.save(file.getAbsolutePath() + fileName,true,10);
            uploadFile();
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    private void uploadFile(){
        if (bitmapFile != null) {
            RequestBody type = RequestBody.create(MediaType.parse("multipart/form-data"), "ORDER");
            RequestBody requestImgFile = RequestBody.create(MediaType.parse("multipart/form-data"), bitmapFile);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", bitmapFile.getName(), requestImgFile);
            final ApiService apiService = HKHttpUtils.getApiService();
            apiService.uploadBitmap(part, type).enqueue(new HKResponseResultCallBack<UploadResult>() {
                @Override
                public void onSuccess(UploadResult uploadResult) {
                    Log.d(TAG, "onSuccess: ------"+orderId);
                    if (uploadResult != null)
                    handWritingSign(apiService,uploadResult.getId());
//                    deleteSignJPG();
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Log.d(TAG, "onGetDataFailed: ");
                    Toast.makeText(HandSignActivity.this,msg,Toast.LENGTH_LONG).show();
                    mProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Log.d(TAG, "onFailed: ");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        }
    }

    private void handWritingSign(ApiService apiService,long picId){
        apiService.handWritingSign(MainActivity.ticket,orderId,picId).enqueue(new HKResponseResultCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                Log.d(TAG, "onSuccess: ");
                deleteSignJPG();
                MainApplication.getInstance().getEventEmitter().sendEvent("order.onload");

                mProgressBar.setVisibility(View.GONE);
                finish();
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Log.d(TAG, "onGetDataFailed: ");
                Toast.makeText(HandSignActivity.this,msg,Toast.LENGTH_LONG).show();
                mProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Log.d(TAG, "onFailed: ");
                mProgressBar.setVisibility(View.GONE);
            }
        });
    }
    
    private void deleteSignJPG(){
        if (bitmapFile != null){
            boolean delete = bitmapFile.delete();
            if (delete){
//                linePathView.clear();
//                mBitmap.recycle();
                Log.d(TAG, "deleteSignJPG: is delete");
            }else {
                Log.d(TAG, "deleteSignJPG: delete failed");
            }
        }
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBitmap != null){
            mBitmap.recycle();
        }
        if (linePathView != null){
            linePathView.clear();
        }
    }


//    private void test(){
//        List<String> ids = new ArrayList<>();
//        ids.add("1");
//        ids.add("2");
//        ApiService apiService = HKHttpUtils.getApiService();
//        apiService.updateBindImageStatus(MainActivity.ticket,orderId,"ORDER_FINISH_IMAGE",ids).enqueue(new HKResponseResultCallBack<Object>() {
//            @Override
//            public void onSuccess(Object o) {
//                Log.d(TAG, "onSuccess: ");
//            }
//
//            @Override
//            public void onGetDataFailed(int cd, String msg) {
//                Log.d(TAG, "onGetDataFailed: ");
//            }
//
//            @Override
//            public void onFailed(Call call, Throwable t) {
//                Log.d(TAG, "onFailed: ");
//            }
//        });
//    }
}
